react使用ajax可以選用fetch API或react-axios,react-axios是把axios在包裝成components,所以可直接使用標籤方式呼叫ajax,但安裝使需注意dependancies。fetch API或直接使用axios,呼叫時注意react生命周期。
使用Fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
src/Fetch.js
import React, { Component } from 'react';
class Fetch extends React.Component {
constructor(props) {
super(props);
this.state = {
rsobj: {},
isLoaded: false,
error: null
};
}
componentDidMount() {
fetch("https://httpbin.org/get")
.then(res => res.json())
.then((result) => {
this.setState({
isLoaded: true,
rsobj: result
});
},(error) => {
this.setState({
isLoaded: true,
error: error
});
}
)
}
render() {
const { isLoaded, error, rsobj } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<p>{JSON.stringify(rsobj)}</p>
);
}
}
}
export default Fetch;
react-axios
除了安裝react-axios,還需安裝依懶的axios與prop-types,照著文件安裝即可。
https://www.npmjs.com/package/react-axios
src/Axios.js
import React, { Component } from 'react';
import { Get } from 'react-axios';
class Axios extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Get url="https://httpbin.org/get" >
{(error, response, isLoading, onReload) => {
if(error) {
return (<div>Something bad happened: {error.message} <button onClick={() => onReload({ params: { reload: true } })}>Retry</button></div>)
}
else if(isLoading) {
return (<div>Loading...</div>)
}
else if(response !== null) {
return (<div>{JSON.stringify(response)} <br/> <button onClick={() => onReload({ params: { refresh: true } })}>Refresh</button></div>)
}
return (<div>Default message before request is made.</div>)
}}
</Get>
</div>
)
}
}
export default Axios;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Axios from './Axios';
import Fetch from './Fetch';
import registerServiceWorker from './registerServiceWorker';
const App = () => (
<div>
<h1>Fetch</h1>
<Fetch />
<h1>Axios</h1>
<Axios />
</div>
)
ReactDOM.render(
<App />,
document.getElementById('root'));
registerServiceWorker();
輸出畫面
參考資料:
use axios fetch data
https://daveceddia.com/ajax-requests-in-react/